//
//  UIViewController+YZImagePicker.m
//  VET
//
//  Created by 刘文靖 on 2018/6/29.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "UIViewController+YZImagePicker.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <objc/runtime.h>
#import "YZCheckAuthorizationTool.h"
@interface UIViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate>

@property (weak, readonly, nonatomic) UIImagePickerController *imagePicker_Controller;

@end
@implementation UIViewController (YZImagePicker)
#pragma mark - private

- (void)presentImagePickerUsingCamera:(BOOL)useCamera
                        allowsEditing:(BOOL)allowsEditing
                             animated:(BOOL)animated {
    
    [self presentImagePickerUsingCamera:useCamera allowsEditing:allowsEditing animated:animated mediaTypes:@[(NSString *)kUTTypeImage]];
}

/**
 *  根据是否使用摄像头来展示系统的ImagePickerView, 若使用则是拍照, 否则为相册
 *
 *  @param useCamera 是否使用摄像头
 */
- (void)presentImagePickerUsingCamera:(BOOL)useCamera
                        allowsEditing:(BOOL)allowsEditing
                             animated:(BOOL)animated
                           mediaTypes:(NSArray *)mediaTypes{
    void (^presentPicker)(BOOL) = ^(BOOL useCamera) {
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.sourceType = (useCamera ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary);
        
        if (useCamera) {
            cameraUI.showsCameraControls = YES;
        }
        cameraUI.mediaTypes = mediaTypes;
        cameraUI.delegate = self;
        cameraUI.allowsEditing = allowsEditing;
        
        [self presentViewController:cameraUI animated:YES completion:nil];
        objc_setAssociatedObject(self, @selector(imagePicker_Controller), cameraUI, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    };
    
    if (useCamera) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //@"没有可用相机设备"
            return ;
        }
        [YZCheckAuthorizationTool checkCameraAuthorizationGrand:^{
            presentPicker(useCamera);
        } withNoPermission:^{
            NSLog(@"相机未授权！");
        }];
    }
    else {
        [YZCheckAuthorizationTool checkPhotoAlbumAuthorizationGrand:^{
            presentPicker(useCamera);
        } withNoPermission:^{
            NSLog(@"相册未授权！");
        }];
    }
    
}

#pragma mark - public

- (void)choosePicture {
    
    [self yz_presentSelectSheetWithTitle:nil
                       cancelButtonTitle:nil   
               twoOtherButtonTitlesArray:@[@"从相册选择",@"拍照"]
                       firstSelBTHandler:^{
                           [self presentImagePickerUsingCamera:NO allowsEditing:YES animated:YES];
                       }
                      secondSelBTHandler:^{
                          [self presentImagePickerUsingCamera:YES allowsEditing:YES animated:YES];
                      }];
}

- (void)choosePictureFromPhotoLibrary {
    
    [self choosePictureFromPhotoLibraryAnimated:NO];
}

- (void)choosePictureFromPhotoLibraryAnimated:(BOOL)animated {
    
    BOOL hasPhotoLibrary = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
    if (hasPhotoLibrary) {
        [self presentImagePickerUsingCamera:NO allowsEditing:YES animated:animated];
    }
}

- (UIImage *)imageFromPickerVC:(UIImagePickerController *)picker
             gotPicWithDicInfo:(NSDictionary *)dicInfo {
    
    UIImage *image = nil;
    NSString *mediaType = dicInfo[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString*)kUTTypeImage])
    {
        // 先看看有没有编辑过
        image = dicInfo[UIImagePickerControllerEditedImage];
        if (!image) {
            // 没编辑, 就获取原图
            image = dicInfo[UIImagePickerControllerOriginalImage];
            if (!image) {
                NSLog(@"=获取图片失败!");
            }
        }
    }
    
    [self dismissImagePickerViewController];
    return image;
}

- (void)asyncSaveUIImage:(UIImage *)image intoPNGFilePath:(NSString *)filepath {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([image isMemberOfClass:[UIImage class]]) {
            
            // 检查文件名格式是否正确, 不正确则改成png
            NSString *ext = [filepath pathExtension];
            NSString *path = filepath;
            if (![ext isEqualToString:@"png"]) {
                // 先移除文件类型, 再指定为png类型
                path = [[filepath stringByDeletingPathExtension] stringByAppendingPathExtension:@"png"];
            }
            
            // jpeg使用: UIImageJPEGRepresentation
            if ([UIImagePNGRepresentation(image) writeToFile:path atomically:YES]) {
                NSLog(@"图片已成功保存到:%@", path);
            }
            else {
                NSLog(@"图片写入png文件失败..");
            }
        }
        else {
            NSLog(@"传入的image必须为UIImage对象");
        }
    });
}


- (void)dismissImagePicker {
    
    [self dismissViewControllerAnyway];
}

- (BOOL)dismissImagePickerViewController {
    
    UIImagePickerController *pickerVC = objc_getAssociatedObject(self, @selector(imagePicker_Controller));
    
    if (pickerVC) {
        [pickerVC dismissViewControllerAnyway];
        return YES;
    }
    else {
        NSLog(@"没有获取到UIImagePickerController!");
    }
    
    return NO;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [self dismissImagePickerViewController];
}

#pragma mark SelectActionSheet

- (void)yz_presentSelectSheetWithTitle:(NSString *)title
                     cancelButtonTitle:(NSString *)cancelTitle
             twoOtherButtonTitlesArray:(NSArray *)twoOtherTitleArray
                     firstSelBTHandler:(void (^)(void))firstSelBTHandler
                    secondSelBTHandler:(void (^)(void))secondSelBTHandler {
    
    [self yz_presentSelectSheetByController:nil
                                 sheetTitle:title
                          cancelButtonTitle:cancelTitle
                  twoOtherButtonTitlesArray:twoOtherTitleArray
                          firstSelBTHandler:firstSelBTHandler
                         secondSelBTHandler:secondSelBTHandler];
}

- (void)yz_presentSelectSheetByController:(id)controller
                               sheetTitle:(NSString *)title
                        cancelButtonTitle:(NSString *)cancelTitle
                twoOtherButtonTitlesArray:(NSArray *)twoOtherTitleArray
                        firstSelBTHandler:(void (^)(void))firstSelBTHandler
                       secondSelBTHandler:(void (^)(void))secondSelBTHandler {
    
    NSAssert(firstSelBTHandler, @"必须指定第一个选择按钮的执行Block");
    NSAssert(secondSelBTHandler, @"必须指定第二个选择按钮的执行Block");
    
    NSString *cancelTitleStr = cancelTitle?:@"取消";
    
    UIViewController *viewController = controller?:self;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // Create the action.
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitleStr style:UIAlertActionStyleCancel handler:nil];
        
        UIAlertAction *firstOtherAction = [UIAlertAction actionWithTitle:twoOtherTitleArray[0] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            firstSelBTHandler();
        }];
        
        UIAlertAction *secondOtherAction = [UIAlertAction actionWithTitle:twoOtherTitleArray[1] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            secondSelBTHandler();
        }];
        
        // Add the action.
        [alertController addAction:cancelAction];
        [alertController addAction:firstOtherAction];
        [alertController addAction:secondOtherAction];
        
        [viewController presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 释放Controller

- (void)dismissViewControllerAnyway {
    
    [self dismissViewControllerAnywayAnimated:YES];
}

- (void)dismissViewControllerAnywayAnimated:(BOOL)animated{
    
    /*
     presentingViewController: controller that presented this view controller.(present当前控制器的控制器, 即父控制器)
     If neither the current view controller or any of its ancestors were presented modally, the value in this property is nil
     
     presentedViewController: controller that is presented by this view controller.(被当前控制器present的控制器, 即子控制器)
     If the current view controller did not present another view controller modally, the value in this property is nil.
     */
    
    BOOL isPushed = self.presentingViewController.presentedViewController == self.navigationController;
    BOOL isNaviRootVC = self == self.navigationController.viewControllers.firstObject;
    
    if ((self.presentingViewController && !isPushed)
        || (self.presentingViewController && (isPushed && isNaviRootVC))
        || self.presentedViewController) {
        
        // The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.
        // 具体参照文档..Discuss中有例子
        
        [self dismissViewControllerAnimated:animated completion:nil];
    }
    else if (self.navigationController){
        [self.navigationController popViewControllerAnimated:animated];
    }
    else {
        NSLog(@"没有找到父视图控制器");
    }
    
}
@end
